import React, { Component } from 'react'
import { getContext } from '@/context/common/applicationContext'
import { withRouterContext } from '@/context/router/routerContext.js'
import { Spin, Menu } from 'antd'
import UserBasicInfo from '@/pages/home/personalCenter/userBasicInfo'
import ParamManage from '@/pages/home/personalCenter/paramManage'
import { UserOutlined, ControlOutlined, SettingOutlined, BookOutlined, DatabaseOutlined } from '@ant-design/icons';
import FileManage from './fileManage'
import SqlManage from './sqlManage'
import { get } from '@/utils/requestUtil'
import BadgeManage from './badgeManage'
import ThemeStyles from './themeStyles'
import PersonalBlogClassification from './personalBlogClassification'
import InterfaceMonitor from './interfaceMonitor'
import BlackListManage from './blackListManage'
import PersonalHomePage from './personalHome'
import BlogRecyclingSite from './BlogRecyclingSite'
import HomePageRecommend from './homePageRecommend'
import BlogAuditManage from './blogAuditManage'
import UserManager from './userManager'
import PersonalSafeBox from './personalSafeBox'
import FormSchemaManage from './formSchemaManage'
import TodoManage from './todoManege';
import PrivatePthotoAlbums from './privatePhotoAlbums';
import TabsExt from '@/components/antdExtend/TabsExt'
import './index.css';

/**
 * @author liu_jshan
 * @version 1.0
 * @Date 2024-02-18
 * 
 * 个人中心页面
 */
class PersonalCenter extends Component {

    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            activeKey: 'personalHome',
            tabItems: [
                {
                    label: '个人主页',
                    children: this.renderInfo('personalHome'),
                    key: 'personalHome',
                    closable: false
                }
            ],
            menuItems: [
                {
                    key: 'personInfo',
                    label: '个人中心',
                    icon: <UserOutlined />,
                    role: roleArray.mormalLevel,
                    children: [
                        {
                            key: 'personalHome',
                            label: '个人主页',
                            role: roleArray.mormalLevel
                        },
                        {
                            key: 'basicInfo',
                            label: '基本信息',
                            role: roleArray.mormalLevel
                        },
                        {
                            key: 'realNameAuthentication',
                            label: '实名认证',
                            role: roleArray.mormalLevel
                        },
                        {
                            key: 'myBadge',
                            label: '我的徽章',
                            role: roleArray.mormalLevel
                        },
                        {
                            key: 'myTodo',
                            label: '我的待办',
                            role: roleArray.mormalLevel
                        }
                    ]
                },
                {
                    key: 'blogCenter',
                    label: '博客中心',
                    icon: <BookOutlined />,
                    role: roleArray.mormalLevel,
                    children: [
                        {
                            key: 'personalBlogClassification',
                            label: '博客标签',
                            role: roleArray.mormalLevel
                        },
                        {
                            key: 'blogRecyclingSite',
                            label: '博客回收站',
                            role: roleArray.mormalLevel
                        }
                    ]
                },
                {
                    key: 'setUpCenter',
                    label: '设置中心',
                    icon: <SettingOutlined />,
                    role: roleArray.mormalLevel,
                    children: [
                        {
                            key: 'themeStyles',
                            label: '主题样式',
                            role: roleArray.mormalLevel
                        }
                    ]
                },
                {
                    key: 'manageCenter',
                    label: '管理中心',
                    icon: <ControlOutlined />,
                    role: roleArray.adminLevel,
                    children: [
                        {
                            key: 'fileManage',
                            label: '附件管理',
                            role: roleArray.adminLevel
                        },
                        {
                            key: 'badgeManage',
                            label: '徽章管理',
                            role: roleArray.adminLevel
                        },
                        {
                            key: 'interfaceMonitor',
                            label: '接口监控',
                            role: roleArray.adminLevel
                        },
                        {
                            key: 'blackListManage',
                            label: '黑名单管理',
                            role: roleArray.adminLevel
                        },
                        {
                            key: 'homePageRecommend',
                            label: '首页推荐',
                            role: roleArray.adminLevel
                        },
                        {
                            key: 'blogAuditManage',
                            label: '博客审核',
                            role: roleArray.adminLevel
                        }
                    ]
                },
                {
                    key: 'SystemConfiguration',
                    label: '系统配置',
                    icon: <DatabaseOutlined />,
                    role: roleArray.superLevel,
                    children: [
                        {
                            key: 'paramManage',
                            label: '参数配置',
                            role: roleArray.superLevel
                        },
                        {
                            key: 'sqlManage',
                            label: '语句配置',
                            role: roleArray.superLevel
                        },
                        {
                            key: 'formSchemaManage',
                            label: '表单配置',
                            role: roleArray.superLevel
                        },
                        {
                            key: 'userManager',
                            label: '用户管理',
                            role: roleArray.superLevel
                        }
                    ]
                },
                {
                    key: 'safeCenter',
                    label: '安全中心',
                    icon: <BookOutlined />,
                    role: roleArray.mormalLevel,
                    children: [
                        {
                            key: 'personalSafeBox',
                            label: '个人保险柜',
                            role: roleArray.mormalLevel
                        },
                        {
                            key: 'privatePthotoAlbums',
                            label: '个人相册',
                            role: roleArray.mormalLevel
                        }
                    ]
                }
            ],
            openKeys: ['personInfo'],
            rootSubmenuKeys: ['personInfo'],
            collapsed: false //导航栏是否收缩
        }
    }

    async componentDidMount() {
        let collapsed = false
        if (window.innerWidth <= 910) collapsed = true
        await new Promise(resolve => {
            this.setState({
                collapsed
            }, resolve)
        })
        //根据用户角色决定展示的页签内容
        let role = 'normal'
        const response = await get('/auth/get/role')
        if (response) role = response.data
        const menuItems = this.state.menuItems
        const newMenuItems = this.createMenuByRole(menuItems, role)
        await new Promise(resolve => {
            this.setState({
                menuItems: newMenuItems,
                loading: false
            }, resolve)
        })
        this.props.setContextValue && this.props.setContextValue({ updateTab: this.updateTab })
        window.addEventListener('resize', this.windowResize) //添加窗口监听
    }

    async componentWillUnmount() {
        window.removeEventListener('resize', this.windowResize)
    }

    //tab页签变化
    onTabChange = async (newActiveKey) => {
        await new Promise(resolve => { this.setState({ activeKey: newActiveKey }, resolve) })
    }

    //菜单栏变化
    onOpenChange = async (keys) => {
        const { openKeys, rootSubmenuKeys } = this.state
        const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
        if (latestOpenKey && rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            await new Promise(resolve => { this.setState({ openKeys: keys }, resolve) })
        } else {
            await new Promise(resolve => { this.setState({ openKeys: latestOpenKey ? [latestOpenKey] : [] }, resolve) })
        }
    }

    //菜单栏点击事件
    onMenuClick = async ({ key, keyPath }) => {
        const { tabItems, menuItems } = this.state
        //先去页签里找是否已存在该页签
        const tabItem = tabItems.find(item => item.key === key)
        if (tabItem) { //如果存在，则直接跳转到相应页签
            await this.onTabChange(key)
        } else { //不能存在，则需要加载一个新的页签
            const menuItem = this.getMenuItem(menuItems, key)
            const newTabItems = [
                ...tabItems,
                {
                    label: menuItem.label,
                    children: this.renderInfo(key),
                    key: key
                }
            ]
            await new Promise(resolve => {
                this.setState({
                    tabItems: newTabItems,
                    activeKey: key
                }, resolve)
            })
        }
    }

    /**
     * 更新或添加一个新的标签页
     * 
     * 此函数用于更新现有标签页或添加新标签页它接受标签页的标识符（key）、显示名称（label）和对应的组件（component）
     * 首先，它会过滤掉与给定key相同的任何现有标签页，然后将新的标签页信息添加到tabItems数组中
     * 最后，它更新组件的状态，设置tabItems为新的数组，并将activeKey设置为新添加的标签页的key
     * 
     * @param {Object} tabInfo - 包含标签页信息的对象
     * @param {string} tabInfo.label - 标签页的显示名称
     * @param {string} tabInfo.key - 标签页的唯一标识符
     * @param {React.Component} tabInfo.component - 标签页对应的React组件
     */
    updateTab = ({ label, key, component }) => {
        // 获取当前的tabItems数组
        const { tabItems } = this.state;

        // 使用新的数组来更新状态
        const newTabItems = tabItems.map(item => {
            if (item.key === key) {
                return { ...item, label, children: component };
            }
            return item
        })

        // 如果没有找到匹配的标签页，则添加新的标签页
        if (!newTabItems.some(item => item.key === key)) {
            newTabItems.push({
                label,
                children: component,
                key
            })
        }

        // 使用函数式更新来确保状态更新的一致性
        this.setState({
            tabItems: newTabItems,
            activeKey: key
        })
    }

    onTabRemove = async (targetKey) => {
        const { tabItems, activeKey } = this.state
        const targetIndex = tabItems.findIndex((pane) => pane.key === targetKey);
        const newPanes = tabItems.filter((pane) => pane.key !== targetKey);
        if (newPanes.length && targetKey === activeKey) {
            const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
            await new Promise(resolve => this.setState({ activeKey: key }, resolve))
        }
        await new Promise(resolve => this.setState({ tabItems: newPanes }, resolve))
    }

    onTabEdit = async (targetKey, action) => {
        if (action === 'remove') {
            await this.onTabRemove(targetKey);
        }
    }

    //用户基本信息页面
    renderInfo = (label) => {
        switch (label) {
            case 'personalHome':  //个人主页
                return <PersonalHomePage />;
            case 'basicInfo': //基本信息
                return <UserBasicInfo user={this.props.user} />;
            case 'realNameAuthentication':
                return '';
            case 'myBadge':
                return '';
            case 'paramManage':
                return <ParamManage />;
            case 'fileManage':
                return <FileManage />;
            case 'sqlManage':
                return <SqlManage />;
            case 'badgeManage':
                return <BadgeManage />;
            case 'themeStyles':
                return <ThemeStyles />;
            case 'personalBlogClassification':
                return <PersonalBlogClassification user={this.props.user} />;
            case 'interfaceMonitor':
                return <InterfaceMonitor />;
            case 'blackListManage':
                return <BlackListManage />;
            case 'blogRecyclingSite':
                return <BlogRecyclingSite user={this.props.user} />;
            case 'homePageRecommend':
                return <HomePageRecommend />;
            case 'blogAuditManage':
                return <BlogAuditManage />;
            case 'userManager':
                return <UserManager />;
            case 'personalSafeBox':
                return <PersonalSafeBox user={this.props.user} />;
            case 'formSchemaManage':
                return <FormSchemaManage />;
            case 'myTodo':
                return <TodoManage />;
            case 'privatePthotoAlbums':
                return <PrivatePthotoAlbums user={this.props.user} />;
            default:
                return null;
        }
    }

    //递归获取菜单项
    getMenuItem = (menuItems, key) => {
        let menuItem = menuItems.find(item => key === item.key)
        if (menuItem) {
            return menuItem
        } else {
            for (let i = 0; i < menuItems.length; i++) {
                if (Array.isArray(menuItems[i].children) && menuItems[i].children.length > 0) {
                    menuItem = this.getMenuItem(menuItems[i].children, key)
                    if (menuItem) return menuItem
                }
            }
        }
    }

    //根据权限创建菜单
    createMenuByRole = (menuItems, role) => {
        return menuItems.filter(menu => {
            if (menu.role.includes(role)) {
                if (menu.children && menu.children.length > 0) {
                    menu.children = this.createMenuByRole(menu.children, role);
                }
                return true
            }
            return false
        })
    }

    //监听窗口宽度变化
    windowResize = async () => {
        const { collapsed } = this.state
        const width = window.innerWidth
        if (width <= 910 && collapsed === false) {
            await new Promise((resolve, reject) => {
                this.setState({ collapsed: true }, resolve)
            })
        } else if (width > 910 && collapsed === true) {
            await new Promise((resolve, reject) => {
                this.setState({ collapsed: false }, resolve)
            })
        }
    }

    tabExtClose = (closeKeys) => {
        const { tabItems, activeKey } = this.state
        const newTabItems = tabItems.filter(item => closeKeys.indexOf(item.key) === -1)
        const newActiveKey = closeKeys.indexOf(activeKey) !== -1 ? newTabItems[newTabItems.length - 1].key : activeKey
        this.setState({
            tabItems: newTabItems,
            activeKey: newActiveKey
        })
    }

    render() {
        if (this.state.loading === true) return <Spin />
        return (
            <div className='PersonalCenter-main'>
                <div className='PersonalCenter-main-left'>
                    <Menu
                        mode={this.state.collapsed === false ? 'inline' : 'horizontal'}
                        openKeys={this.state.openKeys}
                        onOpenChange={this.onOpenChange}
                        items={this.state.menuItems}
                        onClick={this.onMenuClick}
                    // inlineCollapsed={this.state.collapsed}
                    />
                </div>
                <div className='PersonalCenter-main-fillLeft'>
                </div>
                <div className='PersonalCenter-main-right'>
                    <TabsExt
                        hideAdd
                        onChange={this.onTabChange}
                        activeKey={this.state.activeKey}
                        type="editable-card"
                        onEdit={this.onTabEdit}
                        items={this.state.tabItems}
                        tabExtClose={this.tabExtClose}
                    />
                </div>
            </div>
        )
    }
}

//角色级别
const roleArray = {
    mormalLevel: ['normal', 'admin', 'superAdmin'], //全员可见
    adminLevel: ['admin', 'superAdmin'], //管理级别可见
    superLevel: ['superAdmin'] //超级管理可见
}

export default withRouterContext(getContext(PersonalCenter))
